package matlab;

import functions.Function;
import functions.FunctionIF;
import matlabcontrol.MatlabConnectionException;
import matlabcontrol.MatlabProxy;
import matlabcontrol.MatlabProxyFactory;

public class MatFunction extends Function {
	private static MatlabProxy proxy;
	private String func;
	static
	{
		MatlabProxyFactory factory = new MatlabProxyFactory();
		try
		{
			proxy = factory.getProxy();
		} catch (MatlabConnectionException e)
		{
			e.printStackTrace();
		}
	}

	public MatFunction(String func)
	{
		this.func = func;
	}

	@Override
	public double eval(double x)
	{
		try
		{
			proxy.eval("clear;");
			proxy.eval("syms x;");
			proxy.eval("g = "+func);
			
			Object[] returnArguments = proxy.returningEval("subs(g, x, "+x+")", 1);
		    //Retrieve the first (and only) element from the returned arguments
		    Object firstArgument = returnArguments[0];
		    //Like before, cast and index to retrieve the double value
		    double value = ((double[]) firstArgument)[0];
			return value;
		} catch (Exception e)
		{
			System.err.println("ERROR IN MATLAB SESSION ......Raed");
			return 0;
		}
	}

	@Override
	public FunctionIF diff()
	{
		try
		{
		    return new MatFunction("diff("+func+", x)");
		} catch (Exception e)
		{
			System.err.println("ERROR IN MATLAB SESSION ......Raed");
			return null;
		}
	}
	public static void done(){
		proxy.disconnect();
	}
	public static void main(String[] args)
	{
		// Testing eval
		Function f = new MatFunction("x^2+8");
		System.out.println(f.eval(9));
		
		// testing diff
		FunctionIF df = f.diff();
		System.out.println(df.eval(9));
		done();
	}
}
